/*
 * @Author: yc
 * @Date: 2020-05-26 20:51:10
 * @LastEditTime: 2020-05-26 22:52:45
 * @FilePath: \server\routes\user.js
 */
const express = require('express')
const md5 = require('blueimp-md5')

const UserModel = require('../models/userModel')

const router = express.Router()

router.post('/api/user/login', (req, res) => {
  const { username, password } = req.body
  UserModel.findOne({username, password: md5(password)})
    .then(user => {
      console.log(user)
      if(user) { //登录成功
        res.cookie('ycadmin', user._id, { maxAge: 1000 * 60 * 60 * 24 })
        res.send({ code: 0, msg: '成功'})
      } else {
        res.send({ code: 1, msg: '用户名或密码不正确!' })
      }
    })
    .catch(err => {
      res.send({code: 1, msg: '登陆异常, 请重新尝试' })
    })
})

router.post('/api/user/register', (req, res) => {
  const { username, password } = req.body
  UserModel.findOne({username})
    .then(user => {
      if(user){
        res.send({code: 1, msg: '此用户已存在' })
      } else{
        return UserModel.create({ username, password: md5(password)})
      }
    })
    .then(user => {
      res.send({code: 0, data: user})
    })
    .catch(err => {
      res.send({code: 1, msg: '添加用户异常, 请重新尝试'})
    })
})

module.exports = router